package top.ivansong.crawler.config;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Configuration
public class RestTemplateConfig {

	private static final int TIME_OUT = 60 * 1000;

	private static final int CONTACT_MAX_COUNT = 128;

	@Bean
	public RestTemplate restTemplate() {
		OkHttpClient httpClient = new OkHttpClient.Builder()
				.connectTimeout(TIME_OUT, TimeUnit.SECONDS)
				.writeTimeout(TIME_OUT, TimeUnit.SECONDS)
				.readTimeout(TIME_OUT, TimeUnit.SECONDS)
				.connectionPool(new ConnectionPool(CONTACT_MAX_COUNT, TIME_OUT, TimeUnit.SECONDS))
				.retryOnConnectionFailure(true)
				.build();

		OkHttp3ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(httpClient);
		return new RestTemplate(factory);
	}
}
